<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form class="form" ref="form" :inline="true">
      <el-form-item label="用户名:">
        <el-input placeholder="请输入你要搜索的用户名" v-model="username"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="primary" @click="layoutSettings.refresh = !layoutSettings.refresh">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-button type="primary" size="default" @click="addAclUser">添加用户</el-button>
    <el-button type="primary" size="default" @click="deleteAll">批量删除</el-button>
    <el-table border stripe :data="aclList" style="margin: 10px 0" @select="tableSelect">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column type="index" label="#" align="center"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column label="用户名字" align="center" prop="name"></el-table-column>
      <el-table-column label="用户名称" align="center" prop="username"></el-table-column>
      <el-table-column label="用户角色" align="center" prop="roleName"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template #="{ row, $index }">
          <el-button type="primary" size="small" icon="edit" @click="editAclUser(row)">
            编辑
          </el-button>
          <el-popconfirm title="你确定要删除该用户吗?" @confirm="deleteRole(row)">
            <template #reference>
              <el-button type="danger" size="small" icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" size="small" icon="user" @click="getRole(row)">
            分类角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="changeCurrent"
      v-model:currentPage="currentPage"
      :page-sizes="[3, 4, 6, 9]"
      v-model:pageSize="pageSize"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="totalNum"
      background
      :pager-count="7"
    ></el-pagination>
  </el-card>
  <el-drawer
    :title="`${userForms.id ? '修改用户' : '添加用户'}`"
    v-model="drawerShow"
    direction="rtl"
    size="30%"
    :destroy-on-close="true"
    :show-close="true"
    :wrapperClosable="true"
  >
    <el-form ref="form" :inline="false" size="normal" :model="userForms" :rules="rules">
      <el-form-item label="用户姓名" prop="username">
        <el-input v-model="userForms.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="name">
        <el-input v-model="userForms.name"></el-input>
      </el-form-item>
      <el-form-item label="用户密码" prop="password" v-if="!userForms.id">
        <el-input v-model="userForms.password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="getAclUser">确定</el-button>
      <el-button>取消</el-button>
    </template>
  </el-drawer>
  <el-drawer
    title="分配角色（职位）"
    direction="rtl"
    size="30%"
    v-model="drawerShow2"
    :destroy-on-close="true"
    :show-close="true"
    :wrapperClosable="true"
  >
    <el-form label-width="80px" :inline="false" size="normal">
      <el-form-item label="用户姓名">
        <el-input :value="userForms.username" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="职位列表" size="normal">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox-group v-model="assignRoles" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="city in allRolesList" :key="city" :label="city" :value="city">
            {{ city.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="addRole">确定</el-button>
      <el-button type="primary" size="default">取消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import {
  reqAclList,
  reqAddOrUpdateUer,
  reqaddRole,
  reqdeleteAllRole,
  reqdeleteRole,
  reqgetRoleList,
} from '@/api/user'
import type {
  aclListRes,
  aclRecords,
  aclRecordsObj,
  addRoleData,
  roleListData,
  roleListRes,
} from '@/api/user/type'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import useLayoutSettings from '@/stores/modeles/settings'
let layoutSettings = useLayoutSettings()
let currentPage = ref<number>(0)
let pageSize = ref<number>(3)
let totalNum = ref<number>(99)
let aclList = ref<aclRecords>([])
let drawerShow = ref<boolean>(false)
let drawerShow2 = ref<boolean>(false)
let checkAll = ref<boolean>(false)
let isIndeterminate = ref<boolean>(false)
let allRolesList = ref<roleListData[]>([])
let assignRoles = ref<roleListData[]>([])
let selectArr = ref<number[]>([])
let username = ref<string>('')
let userForms = reactive<aclRecordsObj>({
  username: '',
  name: '',
  password: '',
})
let form = ref()
onMounted(() => {
  getAclList()
})
const search = async() => {
  getAclList(currentPage.value,username.value)
}
const deleteAll = async () => {
  let res:any = await reqdeleteAllRole(selectArr.value)
  if(res.code == 200) {
    ElMessage({
      message : '删除成功'
    })
    getAclList(aclList.value.length < 1 ? currentPage.value - 1 : currentPage.value)
  }else {
    ElMessage({
      message : '删除失败'
    })
  }
}
const tableSelect = (role: aclRecordsObj[]) => {
   selectArr.value = role.map(item => item.id as number)
}
const deleteRole = async (row: aclRecordsObj) => {
  let res: any = await reqdeleteRole(row.id as number)
  if (res.code == 200) {
    ElMessage({
      message: '删除成功',
    })
    getAclList(aclList.value.length < 1 ? currentPage.value - 1 : currentPage.value)
  } else {
    ElMessage({
      message: '删除失败',
    })
  }
}

const handleCheckAllChange = (val: boolean) => {
  assignRoles.value = val ? allRolesList.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRolesList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRolesList.value.length
}
const addRole = async () => {
  let data: addRoleData = {
    userId: userForms.id as number,
    roleIdList: assignRoles.value.map((item) => {
      return item.id as number
    }),
  }
  let res: any = await reqaddRole(data)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '更新成功',
    })
    getAclList(currentPage.value)
  } else {
    ElMessage({
      type: 'error',
      message: '更新失败',
    })
  }
  drawerShow2.value = false
}

const getRole = async (row: aclRecordsObj) => {
  drawerShow2.value = true
  Object.assign(userForms, row)
  let res: roleListRes = await reqgetRoleList(row.id as number)
  if (res.code == 200) {
    allRolesList.value = res.data.allRolesList
    assignRoles.value = res.data.assignRoles
  }
}

const changeCurrent = (pager: number) => {
  getAclList(pager)
}
const addAclUser = () => {
  drawerShow.value = true
  Object.assign(userForms, {
    username: '',
    name: '',
    password: '',
  })
  if (userForms.id) delete userForms.id
}
const editAclUser = (row: aclRecordsObj) => {
  drawerShow.value = true
  Object.assign(userForms, row)
}
const getAclUser = async () => {
  await form.value.validate()
  let res: any = await reqAddOrUpdateUer(userForms)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: `${userForms.id ? '修改成功' : '添加成功'}`,
    })
    getAclList()
    if (userForms.id) window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: `${userForms.id ? '修改失败' : '添加失败'}`,
    })
  }
  drawerShow.value = false
}
const rules = {
  username: [
    { required: true, trigger: 'blur', message: '请输入用户名' },
    { min: 5, max: 20, trigger: 'blur', message: '长度应在5-20位之间' },
  ],
  name: [
    { required: true, trigger: 'blur', message: '请输入名称' },
    { min: 5, max: 20, trigger: 'blur', message: '长度应在5-20位之间' },
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码' },
    { min: 5, max: 20, trigger: 'blur', message: '长度应在5-20位之间' },
  ],
}

const getAclList = async (pager = 1,username?:string) => {
  currentPage.value = pager
  let res: aclListRes = await reqAclList(currentPage.value, pageSize.value,username)
  if (res.code == 200) {
    totalNum.value = res.data.total
    aclList.value = res.data.records
  }
}
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-content: center;
  height: 40px;
}
</style>
